﻿using System;
using System.Collections.Generic;
using Business;

public partial class Pages_Home : Business.Security.AdminPage
{
    protected void Page_Load(object sender, EventArgs e)
    {
            if (Session[SessionManager.SessionUserid] == null) 
            Response.Redirect(Config.ApplicationUrl + "authen.html");
       
    }
    protected void Page_Init(object sender, EventArgs e)
    {
        if (Session[SessionManager.SessionUserid] == null) 
        {
            Session.Abandon();
            Response.Redirect(Config.ApplicationUrl + "authen.html");
        }
        try
        {
            LoadControl();

        }
        catch (Exception ex)
        {
            Config.WriteLog(ex.Message + Environment.NewLine + ex.StackTrace);
            ltrError.Text = ex.Message;
            MultiView1.SetActiveView(ViewError);
            Config.Message(Page, "Có lỗi trong quá trình xử lý", "Thông báo lỗi");
        }
    }
    private void LoadControl()
    {
        int id;
        int.TryParse(Request["id"], out id);
        if (id == 0 && !string.IsNullOrEmpty(Request["id"]))
            int.TryParse(Request["id"].Split(',')[0], out id);
        var functions = (List<Functions>)Session[SessionManager.SessionFunctions];
        if (!functions.Exists(c => c.FunctionID == id))
        {
            Title = "Hệ thống quản trị.";
            MultiView1.SetActiveView(ViewError);
            return;
        }
        var control = functions.Find(c => c.FunctionID == id);
        var historyid = Session[SessionManager.SessionHistory] != null
                            ? int.Parse(Session[SessionManager.SessionHistory].ToString())
                            : 0;

        if (control.FatherID != historyid)
        {
            var father = functions.Find(c => c.FunctionID == control.FatherID);
            control = father.FatherID == 0 ? control : father;
        }
        if (functions.Find(c => c.FunctionID == control.FatherID).FatherID == 0)
        {
            Session[SessionManager.SessionPermission] =
              new UserFunctions
                  {
                      UserID = Config.UserId,
                      FunctionID = control.
                                             FunctionID
                  }.UserFunctions_CheckPermissionForUser();
            Session[SessionManager.SessionHistory] = control.FunctionID;
        }
        Page.Title = "Hệ thống quản trị - " + control.Name;
        var Usercontrol = LoadControl(control.Url);
        Session[SessionManager.SessionUserControl] = Usercontrol;
        Content.Controls.Add(Usercontrol);
        MultiView1.SetActiveView(ViewControl);


    }

}
